package com.carey.blog.filter;

import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import com.carey.blog.listener.CareyBlogServletListener;
import com.carey.blog.util.Preferences;

/**
 * Checks initialization filter.
 * 
 */
public final class InitCheckFilter implements Filter {

	/**
	 * Logger.
	 */
	private static final Logger LOGGER = Logger.getLogger(InitCheckFilter.class
			.getName());
	/**
	 * Preference utilities.
	 */
	private Preferences preferenceUtils = Preferences.getInstance();

	@Override
	public void init(final FilterConfig filterConfig) throws ServletException {
	}

	/**
	 * If Carey Blog has not been initialized, so redirects to /init.do.
	 * 
	 * @param request
	 *            the specified request
	 * @param response
	 *            the specified response
	 * @param chain
	 *            filter chain
	 * @throws IOException
	 *             io exception
	 * @throws ServletException
	 *             servlet exception
	 */
	@Override
	public void doFilter(final ServletRequest request,
			final ServletResponse response, final FilterChain chain)
			throws IOException, ServletException {
		final HttpServletRequest httpServletRequest = (HttpServletRequest) request;

		try {
			final String requestURI = httpServletRequest.getRequestURI();
			if (CareyBlogServletListener.isInited()) {
				chain.doFilter(request, response);

				return;
			}

			if (PageCacheFilter.shouldSkip(requestURI)) {
				LOGGER.log(Level.FINEST, "Skip filter request[URI={0}]",
						requestURI);
				chain.doFilter(request, response);

				return;
			}

			// Try to get preference to confirm whether the preference exist
			final JSONObject preference = preferenceUtils.getPreference();
			if (null == preference) {
				LOGGER.warning("Carey Blog has not been initialized, so redirects to /init.do");
				final RequestDispatcher requestDispatcher = httpServletRequest
						.getRequestDispatcher("/init.do");
				requestDispatcher.forward(request, response);
			} else {
				// XXX: Wrong state of CareyBlogServletListener.isInited()
				chain.doFilter(request, response);
				return;
			}
		} catch (final Exception e) {
			((HttpServletResponse) response)
					.sendError(HttpServletResponse.SC_NOT_FOUND);

			return;
		}
	}

	@Override
	public void destroy() {
	}
}
